package com.sunny.ynhz.ui.patrol;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.FileTypeMoreStyleAdapter;
import com.sunny.ynhz.adapter.ImageMoreStyleAdapter;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.api.okhttp.OkHttpHelper;
import com.sunny.ynhz.bean.FileBean;
import com.sunny.ynhz.bean.ImageBean;
import com.sunny.ynhz.bean.PatrolMoreStyleBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.ui.base.AppBaseTranslationTitleBarActivity;
import com.sunny.ynhz.utils.BeanUtils;
import com.sunny.ynhz.utils.GridSpacingItemDecoration;
import com.sunny.ynhz.utils.PictureUtil;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.TimeValueUtils;
import com.sunny.ynhz.utils.ToastUtils;
import com.sunny.ynhz.utils.UUIDUtils;
import com.sunny.ynhz.widget.customdatepicker.widget.CustomDatePicker;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import io.realm.Realm;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/11/9.
 */
public class PatrolRiverMoreStyleActivity extends AppBaseTranslationTitleBarActivity {
    @BindView(R.id.rl_img)
    RecyclerView imagesRecylerView;
    @BindView(R.id.rl_fujian)
    RecyclerView rl_fujian;
    @BindView(R.id.tv_des)
    EditText tv_des;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.ic_check)
    CheckBox ic_check;
    ArrayList<String> imagesPath = new ArrayList<>();
    ArrayList<String> filePath = new ArrayList<>();
    private ImageMoreStyleAdapter imageAdapter;
    private FileTypeMoreStyleAdapter fileTypeMoreStyleAdapter;
    String imgs = "";
    String files = "";
    String filenames = "";
    private PatrolMoreStyleBean patrolMoreStyleBean;

    private CustomDatePicker customDatePicker;

    private Realm mRealm;

    private String moreStyleId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.river_more_activity);
        tv_time.setText(TimeValueUtils.getStringDate());
        setTitle("巡河多样化");
        mRealm = RealmUtils.getDeleteRealm();
        initList();
        imagesRecylerView.setAdapter(imageAdapter);
        rl_fujian.setAdapter(fileTypeMoreStyleAdapter);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        tv_time.setText(now);
        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_time.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(true); // 显示时和分
        customDatePicker.setIsLoop(true); // 允许循环滚动

        moreStyleId = getIntent().getStringExtra("moreStyleId");
        if (moreStyleId != null) {
            patrolMoreStyleBean = mRealm.where(PatrolMoreStyleBean.class).equalTo("id", moreStyleId).findFirst();
            // TODO: 2017/11/16 把对象的值填到文本框里，图片添加到表里
            tv_des.setText(patrolMoreStyleBean.getDescribe());
            tv_time.setText(patrolMoreStyleBean.getTm());

            String[] images = patrolMoreStyleBean.getPicUrl().split(",");
            if (!patrolMoreStyleBean.getPicUrl().isEmpty()) {
                imagesPath.clear();
                imagesPath.addAll(new ArrayList<String>(java.util.Arrays.asList(images)));
                imageAdapter.notifyDataSetChanged();
            }
            String[] files = patrolMoreStyleBean.getFileUrl().split(",");
            if (!patrolMoreStyleBean.getFileUrl().isEmpty()) {
                filePath.clear();
                filePath.addAll(new ArrayList<String>(java.util.Arrays.asList(files)));
                fileTypeMoreStyleAdapter.notifyDataSetChanged();
            }
        }
    }

    public void initList() {
        imagesRecylerView.setLayoutManager(new GridLayoutManager(this, 4));
        imagesRecylerView.addItemDecoration(new GridSpacingItemDecoration(4, 20, false));
        imagesRecylerView.setItemAnimator(new DefaultItemAnimator());
        imageAdapter = new ImageMoreStyleAdapter(this, imagesPath);
        rl_fujian.setLayoutManager(new GridLayoutManager(this, 4));
        rl_fujian.addItemDecoration(new GridSpacingItemDecoration(4, 20, false));
        rl_fujian.setItemAnimator(new DefaultItemAnimator());
        fileTypeMoreStyleAdapter = new FileTypeMoreStyleAdapter(this, filePath);

    }

    @OnClick({R.id.tv_sumbit, R.id.tv_time, R.id.cancel, R.id.save_draft})
    public void onclick(View view) {
        if (view.getId() == R.id.tv_time) {
            // 日期格式为yyyy-MM-dd HH:mm
            customDatePicker.show(tv_time.getText().toString());
        } else if (view.getId() == R.id.cancel) {
            finish();
        } else if (view.getId() == R.id.save_draft) {
            mRealm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    //如果对象的id是空的，说明表里还没存，要重新创建一个对象，如果有就直接重新赋值
                    if (patrolMoreStyleBean == null) {
                        patrolMoreStyleBean = realm.createObject(PatrolMoreStyleBean.class, UUIDUtils.getRandomUUID());
                    }
                    patrolMoreStyleBean.setUserId(SPUtil.get("userId", "null").toString());

                    imgs = "";
                    files = "";
                    for (String filepath : imagesPath) {
                        if (TextUtils.isEmpty(imgs)) {
                            imgs = filepath;
                        } else {
                            imgs = filepath + "," + imgs;
                        }
                    }
                    for (String filepath : filePath) {
                        if (TextUtils.isEmpty(files)) {
                            files = filepath;
                        } else {
                            files = filepath + "," + files;
                        }
                    }
                    patrolMoreStyleBean.setPicUrl(imgs);
                    patrolMoreStyleBean.setPicNums(imgs.isEmpty() ? 0 : imgs.split(",").length);
                    patrolMoreStyleBean.setFileUrl(files);
                    patrolMoreStyleBean.setFileNums(files.isEmpty() ? 0 : files.split(",").length);
                    patrolMoreStyleBean.setFileName(filenames);
                    patrolMoreStyleBean.setDescribe(TextUtils.isEmpty(tv_des.getText().toString()) ? "" : tv_des.getText().toString());
                    patrolMoreStyleBean.setTm(tv_time.getText() + "");
                    ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "保存草稿成功！");
                    finish();
                }
            });
        } else {
            imgs = "";
            files = "";
            if (TextUtils.isEmpty(tv_des.getText().toString())) {
                ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "描述不能为空");
                return;
            }
            if (TextUtils.isEmpty(tv_time.getText().toString())) {
                ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "时间不能为空");
                return;
            }
            if (imagesPath.size() == 0 && filePath.size() == 0) {
                ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "文件类或图片类必须要提交一个");
                return;
            }

            Observable<FileBean> fileBeanObservable = uploadFile(pathToFile(filePath));
            Observable<ImageBean> imageBeanObservable = uploadImgs(pathToFile(imagesPath));
            Observable.merge(fileBeanObservable, imageBeanObservable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
                @Override
                public void onCompleted() {
                    upLoadMsg();
                }

                @Override
                public void onError(Throwable e) {
                    ShowUtils.closePopwindow();
                }

                @Override
                public void onNext(Object o) {
                    if (o instanceof ImageBean) {
                        ImageBean image = (ImageBean) o;
                        if (TextUtils.isEmpty(imgs)) {
                            imgs = NetUrl.imageBaseUrl + image.getNewPath();
                        } else {
                            imgs = NetUrl.imageBaseUrl + image.getNewPath() + "," + imgs;
                        }

                    } else if (o instanceof FileBean) {
                        FileBean image = (FileBean) o;
                        if (TextUtils.isEmpty(files)) {
                            files = NetUrl.imageBaseUrl + image.getNewPath();
                        } else {
                            files = NetUrl.imageBaseUrl + image.getNewPath() + "," + files;
                        }
                    }
                }

                @Override
                public void onStart() {
                    super.onStart();
                    ShowUtils.inItPopwin(PatrolRiverMoreStyleActivity.this, "请等待");
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && data != null) {//图片类
            ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
            if (stringArrayListExtra != null) {
                imagesPath.clear();
                imagesPath.addAll(stringArrayListExtra);
                imageAdapter.notifyDataSetChanged();
            }
        }
        if (requestCode == 205 && data != null) {//文件类
            ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra("paths");
            if (stringArrayListExtra != null) {
                filePath.clear();
                filePath.addAll(stringArrayListExtra);
                fileTypeMoreStyleAdapter.notifyDataSetChanged();
            }

        }
    }

    private Observable<ImageBean> uploadImgs(final List<File> mlist) {
        return Observable.from(mlist).flatMap(new Func1<File, Observable<ImageBean>>() {
            @Override
            public Observable<ImageBean> call(File file) {
                //压缩图片
                Bitmap bitmap = PictureUtil.getSmallBitmap(file.getPath());
                File fileCompressed = PictureUtil.compressImage(bitmap, file.getName());
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), fileCompressed);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                return HttpManager.getInstance().uploadImgs("www", body);
            }
        });
    }

    private Observable<FileBean> uploadFile(List<File> mlist) {
        return Observable.from(mlist).flatMap(new Func1<File, Observable<FileBean>>() {
            @Override
            public Observable<FileBean> call(File file) {
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                if (TextUtils.isEmpty(filenames)) {
                    filenames = file.getName();
                } else {
                    filenames = file.getName() + "," + filenames;
                }
                return HttpManager.getInstance().uploadFiles(System.currentTimeMillis() + "", body);
            }
        });
    }

    public List<File> pathToFile(ArrayList<String> filePath) {
        List<File> files = new ArrayList<>();
        for (int i = 0; i < filePath.size(); i++) {
            files.add(new File(filePath.get(i)));
        }
        return files;
    }

    @TargetApi(24)
    public void upLoadMsg() {
        patrolMoreStyleBean = new PatrolMoreStyleBean();
        patrolMoreStyleBean.setUserId(SPUtil.get("userId", "null").toString());
        patrolMoreStyleBean.setPicUrl(imgs);
        patrolMoreStyleBean.setPicNums(imgs.isEmpty() ? 0 : imgs.split(",").length);
        patrolMoreStyleBean.setFileUrl(files);
        patrolMoreStyleBean.setFileNums(files.isEmpty() ? 0 : files.split(",").length);
        patrolMoreStyleBean.setFileName(filenames);
        patrolMoreStyleBean.setIsImportant(ic_check.isChecked()?"1":"0");
        patrolMoreStyleBean.setDescribe(TextUtils.isEmpty(tv_des.getText().toString()) ? "" : tv_des.getText().toString());
        patrolMoreStyleBean.setTm(tv_time.getText() + ":00");
        OkHttpHelper.postAsyn(NetUrl.baseUrl + "patrolOther/insertPatrolOther", BeanUtils.objectToMap(patrolMoreStyleBean), new OkHttpHelper.ResultCallback<String>() {
            @Override
            public void onResponse(String response) {
                if (moreStyleId != null) {//如查是从草稿箱跳转过来的，提交成功后应该删除草稿箱中的内容。
                    mRealm.beginTransaction();
                    PatrolMoreStyleBean patrolMoreStyleBeanWithDel = mRealm.where(PatrolMoreStyleBean.class).equalTo("id", moreStyleId).findFirst();
                    if (patrolMoreStyleBeanWithDel != null)
                        patrolMoreStyleBeanWithDel.deleteFromRealm();
                        mRealm.commitTransaction();
                }

                ShowUtils.closePopwindow();
                ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "提交成功");
                finish();
            }

            @Override
            public void onError(Request request, Exception e) {
                super.onError(request, e);
                ShowUtils.closePopwindow();
                ToastUtils.SingleToastUtil(PatrolRiverMoreStyleActivity.this, "提交失败");
            }

            @Override
            public void onAfter() {
                super.onAfter();
            }

            @Override
            public void onBefore(Request request) {
                super.onBefore(request);
            }
        }, this);
    }

}
